// Kimi API 配置
const KIMI_API_ENDPOINT = 'https://api.moonshot.cn/v1/chat/completions';
let KIMI_API_KEY = '';

// 从storage中获取API key
chrome.storage.sync.get(['kimiApiKey'], function(result) {
    KIMI_API_KEY = result.kimiApiKey;
});

// 建立与后台脚本的连接
let port = chrome.runtime.connect({ name: 'sidePanel' });
port.onDisconnect.addListener(() => {
    // 重新连接
    port = chrome.runtime.connect({ name: 'sidePanel' });
});

// 获取DOM元素
const sourceText = document.getElementById('sourceText');
const resultText = document.getElementById('resultText');
const summaryResult = document.getElementById('summaryResult');
const translateBtn = document.getElementById('translateBtn');
const clearBtn = document.getElementById('clearBtn');
const copyBtn = document.getElementById('copyBtn');
const summarizeBtn = document.getElementById('summarizeBtn');
const copySummaryBtn = document.getElementById('copySummaryBtn');
const sourceLanguage = document.getElementById('sourceLanguage');
const targetLanguage = document.getElementById('targetLanguage');

// 标签页切换逻辑
const tabButtons = document.querySelectorAll('.tab-button');
const translatePanel = document.getElementById('translate-panel');
const summaryPanel = document.getElementById('summary-panel');

tabButtons.forEach(button => {
    button.addEventListener('click', () => {
        tabButtons.forEach(btn => btn.classList.remove('active'));
        button.classList.add('active');
        
        if (button.dataset.tab === 'translate') {
            translatePanel.style.display = 'block';
            summaryPanel.style.display = 'none';
        } else {
            translatePanel.style.display = 'none';
            summaryPanel.style.display = 'block';
        }
    });
});

// 监听来自background的消息
chrome.runtime.onMessage.addListener((message) => {
    console.log('收到消息:', message);
    if (message.type === 'setSelectedText') {
        sourceText.value = message.text;
        // 自动触发翻译
        translateBtn.click();
    } else if (message.type === 'summarizePage') {
        // 切换到总结标签
        document.querySelector('[data-tab="summary"]').click();
        // 触发总结
        summarizeBtn.click();
    }
});

// 翻译功能
async function translate(text, sourceLang, targetLang) {
    if (!KIMI_API_KEY) {
        alert('请先设置Kimi API Key');
        return;
    }

    try {
        const response = await fetch(KIMI_API_ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${KIMI_API_KEY}`
            },
            body: JSON.stringify({
                messages: [{
                    role: 'user',
                    content: `将以下文本从${sourceLang}翻译成${targetLang}，只返回翻译结果，不要包含任何其他内容：\n${text}`
                }],
                model: 'moonshot-v1-8k',
                temperature: 0.3
            })
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error?.message || '翻译请求失败');
        }

        const data = await response.json();
        
        if (!data || !data.choices || !data.choices[0] || !data.choices[0].message) {
            throw new Error('API返回数据格式错误');
        }

        return data.choices[0].message.content;
    } catch (error) {
        console.error('翻译错误:', error);
        throw new Error(error.message || '翻译失败，请稍后重试');
    }
}

// 页面总结功能
async function summarize(text) {
    if (!KIMI_API_KEY) {
        alert('请先设置Kimi API Key');
        return;
    }

    try {
        const response = await fetch(KIMI_API_ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${KIMI_API_KEY}`
            },
            body: JSON.stringify({
                messages: [{
                    role: 'user',
                    content: `请用简洁的语言总结以下内容的要点（不超过500字）：\n${text}`
                }],
                model: 'moonshot-v1-8k',
                temperature: 0.3
            })
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error?.message || '总结请求失败');
        }

        const data = await response.json();
        
        if (!data || !data.choices || !data.choices[0] || !data.choices[0].message) {
            throw new Error('API返回数据格式错误');
        }

        return data.choices[0].message.content;
    } catch (error) {
        console.error('总结错误:', error);
        throw new Error(error.message || '总结失败，请稍后重试');
    }
}

// 事件监听器
translateBtn.addEventListener('click', async () => {
    const text = sourceText.value.trim();
    if (!text) {
        alert('请输入要翻译的文本');
        return;
    }

    translateBtn.disabled = true;
    try {
        const sourceLangText = sourceLanguage.options[sourceLanguage.selectedIndex].text;
        const targetLangText = targetLanguage.options[targetLanguage.selectedIndex].text;
        
        const result = await translate(
            text,
            sourceLangText,
            targetLangText
        );
        resultText.value = result;
    } catch (error) {
        alert(error.message || '翻译失败，请稍后重试');
    } finally {
        translateBtn.disabled = false;
    }
});

summarizeBtn.addEventListener('click', async () => {
    // 获取当前活动标签页的内容
    chrome.tabs.query({active: true, currentWindow: true}, async function(tabs) {
        const tab = tabs[0];
        chrome.scripting.executeScript({
            target: {tabId: tab.id},
            function: () => document.body.innerText
        }, async (results) => {
            if (results && results[0]) {
                const pageText = results[0].result;
                summarizeBtn.disabled = true;
                try {
                    const summary = await summarize(pageText);
                    summaryResult.value = summary;
                } catch (error) {
                    alert('总结失败：' + error.message);
                } finally {
                    summarizeBtn.disabled = false;
                }
            }
        });
    });
});

clearBtn.addEventListener('click', () => {
    sourceText.value = '';
    resultText.value = '';
});

copyBtn.addEventListener('click', () => {
    resultText.select();
    document.execCommand('copy');
});

copySummaryBtn.addEventListener('click', () => {
    summaryResult.select();
    document.execCommand('copy');
}); 